package com.azzcs.blog.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: wzg
 * @Date: 2021/1/12 下午10:09
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${server.port}")
    private String port;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = request.getSession().getId();
        Object userId = redisTemplate.opsForValue().get(sessionId);
        if(userId == null){
//            request.getRequestDispatcher("/login").forward(request, response);
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String sessionId = request.getSession().getId();
        modelAndView.addObject("port",port);
        modelAndView.addObject("sessionId",sessionId);
    }
}
